<template>
  <!-- 完全保留原始HTML结构 -->
  <div id="main">
    <video id="remoteVideo" playsinline autoplay />
    <video id="localVideo" playsinline autoplay muted />

    <div id="buttons">
      <button id="hangup">挂断</button>
    </div>
  </div>
</template>

<script>
// 保留原始fix-webm-duration.js引用
import '/public/fix-webm-duration.js'
import store from '@/store'

// 保持原始全局变量结构1
const originalVariables = {
  username: '',
  localVideo: null,
  remoteVideo: null,
  websocket: null,
  peer: {},
  candidate: null,
  stream: null,
  callType: '1', // 默认视频
  fromUser: null
}

export default {
  data() {
    return {
      ...originalVariables
    }
  },
  watch: {
    '$store.getters.websocketContent': {
      immediate: true,
      deep: true,
      handler(val) {
        if (val) {
          console.log('页面内收到websocket', val)
          this.$nextTick(() => {
            if (val !== null) {
              this.WebSocketWatch(val)
            }
          })
        }
      }
    }
  },

  mounted() {
    // 完全保留初始化顺序
    this.username = this.$route.query.username

    console.log('123123', this.$route.query)
    if (
      this.$route.query.hasOwnProperty('call') &&
      this.$route.query.call === true
    ) {
      // call为true证明是发送方页面
      this.call(this.$route.query.flag)
    }
    this.localVideo = document.getElementById('localVideo')
    this.remoteVideo = document.getElementById('remoteVideo')

    // 保留原始初始化调用
    this.ButtonFunInit()

    // 保留视频元素隐藏逻辑
    // this.localVideo.style.display = "none";
    // this.remoteVideo.style.display = "none";
  },
  beforeDestroy() {},

  methods: {
    // 完整WebSocket初始化
    async WebSocketWatch(rawData) {
      console.log('//////////', rawData)
      const { type, fromUser, toUser, msg, sdp, iceCandidate, callType } =
        rawData
      // 完整保留所有条件分支
      if (type === 'hangup') {
        console.log('hangup', msg)
        document.getElementById('hangup').click()
        return
      }

      if (type === 'call_start') {
        let msg = '0'
        this.$confirm(`${fromUser}发起语音通话，确定接听吗`, '通话请求', {
          confirmButtonText: '接听',
          cancelButtonText: '拒绝',
          type: 'warning',
          closeOnClickModal: false // 新增此配置项
        })
          .then(async() => {
            await this.WebRTCInit(fromUser)
            msg = '1'
            this.$nextTick(() => {
              this.$store.getters.websocket.send(
                JSON.stringify({
                  type: 'call_back',
                  toUser: fromUser,
                  fromUser: this.username,
                  msg: msg,
                  callType: callType
                })
              )
            })
            this.fromUser = fromUser
          })
          .catch(() => {
            this.$nextTick(() => {
              this.$store.getters.websocket.send(
                JSON.stringify({
                  type: 'call_back',
                  toUser: fromUser,
                  fromUser: this.username,
                  msg: msg,
                  callType: callType
                })
              )
              document.getElementById('hangup').click()
            })
          })

        return
      }

      if (type === 'call_back') {
        if (msg === '1') {
          await this.getVideo(callType)

          if (
            this.peer[fromUser] &&
            this.peer[fromUser].signalingState !== 'closed'
          ) {
            this.stream.getTracks().forEach((track) => {
              this.peer[fromUser].addTrack(track, this.stream)
            })
          }

          console.log('this.peer', this.peer, fromUser)
          const offer = await this.peer[fromUser].createOffer()
          await this.peer[fromUser].setLocalDescription(offer)

          const newOffer = { ...offer }
          console.log(newOffer)
          newOffer['fromUser'] = this.username
          newOffer['toUser'] = this.toUser
          newOffer['callType'] = callType
          this.$store.getters.websocket.send(JSON.stringify(newOffer))
        } else if (msg === '0') {
          alert(this.toUser + '拒绝语音通话')
          document.getElementById('hangup').click()
        } else {
          alert(msg)
        }

        return
      }

      if (type === 'offer') {
        await this.getVideo(callType)

        console.log(this.peer, fromUser, this.stream)
        this.stream.getTracks().forEach((track) => {
          this.peer[fromUser].addTrack(track, this.stream)
        })

        await this.peer[fromUser].setRemoteDescription(
          new RTCSessionDescription({ type, sdp })
        )

        const answer = await this.peer[fromUser].createAnswer()

        const newAnswer = { ...answer }
        console.log(newAnswer)
        newAnswer['fromUser'] = this.username
        newAnswer['toUser'] = fromUser

        this.$store.getters.websocket.send(JSON.stringify(newAnswer))

        await this.peer[fromUser].setLocalDescription(newAnswer)
        return
      }

      if (type === 'answer') {
        this.peer[fromUser].setRemoteDescription(
          new RTCSessionDescription({ type, sdp })
        )
        return
      }

      if (type === '_ice') {
        this.peer[fromUser].addIceCandidate(iceCandidate)
        return
      }

      if (type === 'getStream') {
        WebRTCInit(fromUser)
        this.stream.getTracks().forEach((track) => {
          this.peer[fromUser].addTrack(track, this.stream)
        })

        const offer = await this.peer[fromUser].createOffer()
        await this.peer[fromUser].setLocalDescription(offer)

        const newOffer = { ...offer }
        newOffer['fromUser'] = this.username
        newOffer['toUser'] = fromUser
        this.$store.getters.websocket.send(JSON.stringify(newOffer))
      }
    },

    // 完整保留媒体获取方法
    async getVideo(callType) {
      if (this.stream == null) {
        if (callType == '1') {
          // 音频
          this.stream = await navigator.mediaDevices.getUserMedia({
            // audio: true
            audio: {
              autoGainControl: true,
              echoCancellation: true,
              noiseSuppression: true
            }
          })
        } else if (callType == '2') {
          // 视频
          this.stream = await navigator.mediaDevices.getUserMedia({
            video: {
              width: 2560,
              height: 1440,
              // width: 1280, height: 720,
              // 强制后置
              // facingMode: { exact: "environment" },
              // 前置 如果有的话
              facingMode: 'user',
              // 受限带宽传输时，采用低帧率
              frameRate: { ideal: 25, max: 30 }
            },
            // video: true,
            audio: true
            // audio: {
            //   autoGainControl: true,
            //   echoCancellation: true,
            //   noiseSuppression: true,
            // },
          })
        }
        this.localVideo.srcObject = this.stream
      }
    },

    // 完整保留WebRTC初始化
    WebRTCInit(userId) {
      this.peer = {}
      console.log('/=/*/*/*/*', this.peer)
      // if (this.peer[userId]) {
      //   this.peer[userId].close();
      //   delete this.peer[userId];
      // }

      const p = new RTCPeerConnection()

      p.onicecandidate = (e) => {
        if (e.candidate) {
          this.$store.getters.websocket.send(
            JSON.stringify({
              type: '_ice',
              toUser: userId,
              fromUser: this.username,
              iceCandidate: e.candidate
            })
          )
        }
      }

      p.ontrack = (e) => {
        if (e && e.streams) {
          this.remoteVideo.srcObject = e.streams[0]
        }
      }

      this.peer[userId] = p
      console.log(this.peer)
    },

    // 完整保留通话逻辑
    call(ct) {
      console.log('*******', this.$route.query.toUser)
      this.toUser = this.$route.query.toUser

      this.callType = ct

      if (!this.peer[this.toUser]) {
        this.WebRTCInit(this.toUser)
      }
      this.$store.getters.websocket.send(
        JSON.stringify({
          type: 'call_start',
          fromUser: this.username,
          toUser: this.toUser,
          callType: this.callType
        })
      )
    },

    // 完整保留按钮事件初始化
    ButtonFunInit() {
      document.getElementById('hangup').onclick = async(e) => {
        if (e.isTrusted) {
          // 手动
          console.log(
            'send hangup ',
            JSON.stringify({
              type: 'hangup',
              fromUser: this.username,
              toUser: this.fromUser,
              callType: this.callType
            })
          )
          await this.$store.getters.websocket.send(
            JSON.stringify({
              type: 'hangup',
              fromUser: this.username,
              toUser: this.fromUser,
              callType: this.callType
            })
          )
        }

        if (this.stream) {
          this.stream.getTracks().forEach((track) => track.stop())
          this.stream = null
        }

        if (this.remoteVideo.srcObject) {
          this.remoteVideo.srcObject
            .getTracks()
            .forEach((track) => track.stop())
        }

        Object.keys(this.peer).forEach(async(key) => {
          await this.peer[key].close()
          delete this.peer[key]
        })
        this.peer = {}
        this.$set(this.localVideo, 'srcObject', null)
        this.$set(this.remoteVideo, 'srcObject', null)

        setTimeout(() => {
          this.$nextTick(() => {
            this.$router.push({
              path: '/situation'
            })
          })
        }, 1000)
      }
    }
  }
}
</script>

<style scoped>
/* 完全复制原始CSS样式 */
html,
body {
  margin: 0;
  padding: 0;
}

#main {
  position: absolute;
  width: 100%;
  height: 100%;
}

#localVideo {
  position: absolute;
  background: #757474;
  top: 10px;
  right: 10px;
  width: 200px;
  z-index: 2;
}

#remoteVideo {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #222;
}

#buttons {
  z-index: 3;
  bottom: 20px;
  left: 20px;
  position: absolute;
}

input {
  border: 1px solid #ccc;
  padding: 7px 0;
  border-radius: 5px;
  padding-left: 5px;
  margin-bottom: 5px;
}

input:focus {
  border-color: #66afe9;
  outline: 0;
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075),
    0 0 8px rgba(102, 175, 233, 0.6);
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075),
    0 0 8px rgba(102, 175, 233, 0.6);
}

#call {
  width: 70px;
  height: 35px;
  background-color: #00bb00;
  border: none;
  color: white;
  border-radius: 5px;
}

#hangup {
  width: 70px;
  height: 35px;
  background-color: #ff5151;
  border: none;
  color: white;
  border-radius: 5px;
}

button {
  width: 70px;
  height: 35px;
  margin: 6px;
  background-color: #6de73d;
  border: none;
  color: white;
  border-radius: 5px;
}
</style>
